package com.yicong.ants.ui.circle.home;

import android.graphics.drawable.Drawable;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.graphics.drawable.DrawableCompat;

import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.databinding.CircleHtmlEditActivityBinding;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.UiAssistant;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.manager.loader.GlideEngine2;
import com.yicong.ants.view.RichEditor;

import org.apache.commons.lang3.StringEscapeUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author cch
 * @version 2020/8/22
 */
public class StaticHtmlEditActivity extends BaseTitleBarActivity<CircleHtmlEditActivityBinding> implements View.OnClickListener {
    RichEditor mEditor;
    TextView mPreview;
    public static String mHtmlLink;

    @Override
    protected int getLayout() {
        return R.layout.circle_html_edit_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText("编辑广告");
        mDataBind.setClick(this);
        onLoadData();
        addTitleMenuItem(UiAssistant.getAtyMenuText(mContext, "保存"), view -> {
            //
            Map<String, String> map = new HashMap<>();
            map.put("content", mEditor.getHtml());
            if (getIntent().hasExtra(Constants.Extra.Id)) {
                map.put("id", getIntent().getStringExtra(Constants.Extra.Id));
            }
            showProgress();
            addSubscribe(RetrofitHelper.getApis().saveHtml(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        return;
                    }
                    mHtmlLink = respBean.getData();
                    RxBus.get().postEvent(Constants.Event.Circle_Ad_Html_Suc);
                    finish();
//                     data = respBean.getData();
                }, RxHelper.getHideProgressConsumer(this)));
        });
        initViews();
    }

    private void initViews() {
        mEditor = mDataBind.editor;
        mEditor.setEditorHeight(200);
        mEditor.setEditorFontSize(22);
        mEditor.setEditorFontColor(UiHelper.getColor(R.color.text_222));
        //mEditor.setEditorBackgroundColor(Color.BLUE);
        //mEditor.setBackgroundColor(Color.BLUE);
        //mEditor.setBackgroundResource(R.drawable.bg);
        mEditor.setPadding(10, 10, 10, 10);
        //mEditor.setBackground("https://raw.githubusercontent.com/wasabeef/art/master/chip.jpg");
        mEditor.setPlaceholder("请输入广告展示内容");
        //mEditor.setInputEnabled(false);

        mPreview = mDataBind.preview;
        mEditor.setOnTextChangeListener(text -> {
            //
            mPreview.setText(text);
        });

        if (PrefHelper.contains(Constants.Prefs.Circle_Ad_Draft)
            && !getIntent().hasExtra(Constants.Extra.Id)) {

            UiHelper.showCancelDialog(mContext, "检测到存在草稿，是否恢复编辑？",
                Pair.create("取消", (dialog, which) -> dialog.dismiss()),
                Pair.create("确定", (dialog, which) -> {
                    dialog.dismiss();
                    mEditor.setHtml(PrefHelper.getString(Constants.Prefs.Circle_Ad_Draft));
                }));
        }
    }

    @Override
    protected void onLoadData() {
        if (!getIntent().hasExtra(Constants.Extra.Id)) {
            return;
        }
        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("id", getIntent().getStringExtra(Constants.Extra.Id));
        addSubscribe(RetrofitHelper.getApis().htmlContent(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    return;
                }
                mEditor.setHtml(StringEscapeUtils.unescapeHtml4(respBean.getData()));
            }, RxHelper.getHideProgressConsumer(this)));
    }

    void toggleView(View v) {
        if (!(v instanceof ImageView)) {
            return;
        }
        boolean toggle = v.getTag() == null || "0".equals(v.getTag());
        ImageView view = (ImageView) v;
        Drawable drawable = view.getDrawable();
        DrawableCompat.setTint(drawable, UiHelper.getColor(toggle ? R.color.orange : R.color.text_888));
        view.setImageDrawable(drawable);
        view.setTag(toggle ? "1" : "0");
    }

    @Override
    public void onBackPressed() {
        if (StringHelper.isEmpty(mEditor.getHtml())) {
            finish();
            return;
        }
        if (getIntent().hasExtra(Constants.Extra.Id)) {
            finish();
            return;
        }
        UiHelper.showCancelDialog(mContext, "是否保存草稿?",
            Pair.create("取消", (dialog, which) -> {
                dialog.dismiss();
                finish();
            }),
            Pair.create("保存", (dialog, which) -> {
                PrefHelper.putString(Constants.Prefs.Circle_Ad_Draft, mEditor.getHtml());
                dialog.dismiss();
                finish();
            }));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBackPressed();
                break;
            case R.id.edit_undo:
                mEditor.undo();
                break;
            case R.id.edit_bold:
                mEditor.setBold();
                toggleView(v);
                break;
            case R.id.edit_italic:
                mEditor.setItalic();
                toggleView(v);
                break;
            case R.id.edit_image:
//                PictureSelector.create(this)
//                    .openGallery(PictureMimeType.ofImage())
//                    .selectionMode(PictureConfig.SINGLE)
//                    .isEnableCrop(true)
//                    .freeStyleCropEnabled(true)
//                    .imageEngine(GlideEngine2.createGlideEngine())
//                    .forResult(new OnResultCallbackListener<LocalMedia>() {
//                        @Override
//                        public void onResult(List<LocalMedia> result) {
//                            if (CollectionHelper.isEmpty(result)) {
//                                return;
//                            }
//                            // 结果回调
//                            ImageHelper.uploadImage(mDisposable, result.get(0).getCutPath(), respBean -> {
//                                if (respBean.isCodeFail()) {
//                                    showError();
//                                    return;
//                                }
//                                mEditor.insertImage(respBean.getData(), "alt");
//                            }, throwable -> {
//                                showError();
//                                Logs.logException(throwable);
//                            });
//                        }
//
//                        @Override
//                        public void onCancel() {
//                            // 取消
//                        }
//                    });
                break;
                /*
            case R.id.edit_insert_video:
                mEditor.insertVideo("https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_10MB.mp4"
                    , 360);
                break;*/
            case R.id.edit_link:
                Dialogs.showHtmlLinkEdit(mContext, str -> {
                    String[] arr = str.split("##");
                    mEditor.insertLink(arr[1], arr[0]);
                });
                break;
/*            case R.id.edit_heading1:
                mEditor.setHeading(1);
                break;
            case R.id.edit_heading2:
                mEditor.setHeading(2);
                break;
            case R.id.edit_heading3:
                mEditor.setHeading(3);
                break;*/
            case R.id.edit_align_center:
                toggleView(v);
                if (v.getTag() == "1") {
                    mEditor.setAlignCenter();
                } else {
                    mEditor.setAlignLeft();
                }
                break;
            case R.id.edit_list:
                mEditor.setNumbers();
                toggleView(v);
                break;
        }
    }
}
